package com.gg.client;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;

public class LongClient {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    private InputStream inputStream;

    public LongClient(String serverAddress, int serverPort) throws Exception {
        // 建立连接
        socket = new Socket(serverAddress, serverPort);
        out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
        inputStream = socket.getInputStream();
        in = new BufferedReader(new InputStreamReader(inputStream));

        // 启动监听线程
        new Thread(new Listener()).start();
    }

    // 发送消息的方法
    public void sendMessage(String message) {
        out.println(message);
        System.out.println("Sent: " + message); // 添加调试信息
    }

    // 关闭连接的方法
    public void close() throws Exception {
        in.close();
        out.close();
        socket.close();
    }

    // 监听线程类
    private class Listener implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {

                    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[10240];
                    int ch;
                    if ((ch = inputStream.read(buffer)) == -1) {
                        continue;
                    }
                    bytestream.write(buffer, 0, ch);
                    byte[] data = bytestream.toByteArray();
                    bytestream.close();
                    handleReceivedMessage(data);


                    //String receivedMessage;
                    //while ((receivedMessage = in.readLine()) != null) {
                    //    // 处理接收到的信息
                    //    handleReceivedMessage(receivedMessage);
                    //}
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    // 处理接收到的信息的方法
    private void handleReceivedMessage(byte[] message) {
        System.out.println("Received: " + Arrays.toString(message));
        // 在这里添加对接收到的信息的处理逻辑
    }

    public static void main(String[] args) {
        try {
            LongClient client = new LongClient("localhost", 12345);
            client.sendMessage("Hello, Server!");
            // 保持连接
            //Thread.sleep(60000); // 1分钟后关闭连接
            //client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
